package com.hm.oper_monitor.ui.page.busi;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;

import com.hm.common.util.ResourceUtil;
import com.hm.common.util.SpringUtil;
import com.hm.oper_monitor.bean.ResourcesManager;
import com.hm.oper_monitor.dao.ConfigDao;
import com.hm.oper_monitor.dao.busimonitor.BusiMonitorDao;
import com.hm.oper_monitor.pojo.BusiMonitor;
import com.hm.oper_monitor.pojo.Config;
import com.hm.oper_monitor.ui.tab.TabPanel;

@SuppressWarnings("serial")
public class BusiOperPage extends JPanel {
	// @Autowired
	// BusiMonitorDao busiMonitorDao;
	public static final String tip = "busi_oper";
	public static final String title = "业务运维监控日志";
	private static BusiOperPage page;
	private ResourcesManager rm;
	private JTable busiListTable;
	private BusiConfigTableModel busiConfigTableModel;
	private JTable busiDetailTable;
	private BusiListTableModel busiListTableModel;
	final List<String> columnNames = new ArrayList<String>();
	String[][] configRowData = new String[30][22];
	String[][] rowData = new String[100][22];
	private List<BusiMonitor> busiMonitorList = new ArrayList<BusiMonitor>();
	private List<String[]> busiShowMonitorList;
	final String[] configColumnNames = { "业务编号", "业务名称" };
	private Config selectItem;
	private ConfigDao configDao;
	private BusiMonitorDao busiMonitorDao;
	private Timer timer;
	protected int row;
	// protected int col;
	private int pageNumber = 1;
	private Object lock = new Object();

	private BusiOperPage() {
		rm = SpringUtil.getBean(ResourcesManager.class);
		configDao = SpringUtil.getBean(ConfigDao.class);
		busiMonitorDao = SpringUtil.getBean(BusiMonitorDao.class);
		setPage();
	}

	public static BusiOperPage getPage() {
		if (page == null) {
			synchronized (BusiOperPage.class) {
				if (page == null) {
					page = new BusiOperPage();
				}
			}
		}
		return page;
	}

	public void setPage() {
		busiShowMonitorList = new ArrayList<String[]>();
		timer = timer = new Timer();
		this.setLayout(new BorderLayout());
		this.setBounds(0, 0, rm.getScreenViewProp().getScreenWidth(), rm.getScreenViewProp().getScreenHeight());

		addListener();
		initBusiListTable();
		initBusiDetailTable();
		initButtonPanel();
	}

	public void addListener() {
		TabPanel.getTab().addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				if (rm.isUpdateBusi()) {
					int index = TabPanel.getTab().getSelectedIndex();
					if (index == 1) {
						List<Config> p = configDao.selectPage(null);
						for (int i = 0; i < p.size(); i++) {
							Config config = p.get(i);
							String[] t = { ("" + config.getId()), config.getConfigName(), config.getTableName(),
									config.getPhone(), config.getMessage(), config.getTime(), config.getConfigSql(),
									config.getTranSq(), config.getDisplay() };
							configRowData[i] = t;
						}

						// initBusiDetailTable();
						String firstId = configRowData[0][0];
						if (firstId != null) {
							Config config = new Config();
							config.setId(Integer.parseInt(firstId));
							selectItem = configDao.select(config);
							updateBusiMonitor(selectItem);
						}
						// busiListTableModel.fireTableStructureChanged();
						// busiDetailTable.updateUI();
						// autoFilling();

					}
					rm.setUpdateBusi(false);
				}

			}
		});
	}

	public void initBusiListTable() {
		List<Config> p = configDao.selectPage(null);
		for (int i = 0; i < p.size(); i++) {
			Config config = p.get(i);
			String[] t = { ("" + config.getId()), config.getConfigName(), config.getTableName(), config.getPhone(),
					config.getMessage(), config.getTime(), config.getConfigSql(), config.getTranSq(),
					config.getDisplay() };
			configRowData[i] = t;
		}
		selectItem = new Config();
		String[] selectData = configRowData[0];
		selectItem.setMessage(selectData[2]);
		selectItem.setTableName(selectData[3]);
		selectItem.setPhone(selectData[4]);
		selectItem.setTime(selectData[5]);
		selectItem.setDisplay(selectData[6]);
		busiConfigTableModel = new BusiConfigTableModel();
		busiListTable = new JTable();
		busiListTable.setModel(busiConfigTableModel);
		busiListTable.setPreferredScrollableViewportSize(new Dimension(250, 300));// 设置表格的大小
		busiListTable.setRowHeight(30);// 设置每行的高度为20
		busiListTable.setShowVerticalLines(true);// 是否显示垂直的网格线
		// busiListTable.setValueAt("tt", 0, 0);// 设置某个单元格的值,这个值是一个对象
		busiListTable.doLayout();
		busiListTable.setBackground(new Color(255, 255, 255, 255));
		// busiDetailTable.setBounds(0, 0, 300,
		// rm.getScreenViewProp().getScreenHeight() -100);
		JScrollPane busiListTableScrollpane = new JScrollPane(busiListTable);
		// busiListTable.addRowSelectionInterval(index0, index1);
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
		// tcr.setHorizontalAlignment(JLabel.CENTER);
		busiListTable.getTableHeader().setFont(new Font("Dialog", 0, 14));
		tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样
		busiListTable.setDefaultRenderer(Object.class, tcr);
		busiListTable.addMouseListener(new MouseListener() {

			public void mouseReleased(MouseEvent e) {
			}

			public void mousePressed(MouseEvent e) {
			}

			public void mouseExited(MouseEvent e) {
			}

			public void mouseEntered(MouseEvent e) {
			}

			public void mouseClicked(MouseEvent e) {
				row = ((JTable) e.getSource()).rowAtPoint(e.getPoint()); // 获得行位置
				// col = ((JTable) e.getSource()).columnAtPoint(e.getPoint()); // 获得列位置
				String cellVal = (String) (busiConfigTableModel.getValueAt(row, 0)); // 获得点击单元格数据
				Config config = new Config();
				config.setId(Integer.parseInt(cellVal));
				selectItem = configDao.select(config);
				updateBusiMonitor(selectItem);
				// autoFilling();
			}
		});

		this.add(busiListTableScrollpane, BorderLayout.WEST);
	}

	public void updateBusiMonitor(final Config item) {
		Thread updateThread = new Thread(new Runnable() {
			public void run() {
				synchronized (lock) {
					List<BusiMonitor> dataList = busiMonitorDao.selectPage(item.getSelectSql());
					pageNumber = 1;
					busiMonitorList.clear();
					busiMonitorList = new LinkedList<BusiMonitor>(dataList);
					displayFields(item);
					busiListTableModel.fireTableStructureChanged();
					busiDetailTable.updateUI();
					autoFilling();
					Thread.yield();
				}

			}
		});
		updateThread.start();

	}

	public void initBusiDetailTable() {
		busiDetailTable = new JTable();
		busiListTableModel = new BusiListTableModel();
		busiDetailTable.setModel(busiListTableModel);
		// busiDetailTable.setPreferredScrollableViewportSize(new Dimension(1300,
		// 500));// 设置表格的大小
		busiDetailTable.setRowHeight(30);// 设置每行的高度为20
		busiDetailTable.setShowVerticalLines(true);// 是否显示垂直的网格线
		busiDetailTable.doLayout();
		busiDetailTable.setBackground(new Color(255, 255, 255, 255));
		busiDetailTable.getTableHeader().setFont(new Font("Dialog", 0, 14));
		final JScrollPane scrollpane = new JScrollPane(busiDetailTable);
		scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); // 水平滚动条根据需要才显示
		scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		scrollpane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
			public void adjustmentValueChanged(AdjustmentEvent e) {
				// System.out.println(e.getValue());
				// System.out.println(scrollpane.getVerticalScrollBar().getMaximum());

//				int extent = scrollpane.getVerticalScrollBar().getModel().getExtent();
//				int value = scrollpane.getVerticalScrollBar().getModel().getValue();
//				int maximum = scrollpane.getVerticalScrollBar().getModel().getMaximum();
//				int max = maximum;
//				if (extent + value == max) {
//					pageNumber = pageNumber + 1;
//					refreshData(pageNumber);
//				}
			}
		});
		Thread updateThread = new Thread(new Runnable() {
			public void run() {
				synchronized (lock) {
					List<BusiMonitor> dataList = busiMonitorDao.selectPage(selectItem.getSelectSql());
					busiMonitorList = new LinkedList<BusiMonitor>(dataList);
					displayFields(selectItem);
					autoFilling();
					busiDetailTable.updateUI();
					Thread.yield();
				}
			}
		});
		updateThread.start();
		// busiListTable.addRowSelectionInterval(index0, index1);

		busiDetailTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		// scrollpane.setSize(new Dimension(1000, 1000));
		DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();// 设置table内容居中
		// tcr.setHorizontalAlignment(JLabel.CENTER);
		tcr.setHorizontalAlignment(SwingConstants.CENTER);// 这句和上句作用一样
		busiDetailTable.setDefaultRenderer(Object.class, tcr);

		this.add(scrollpane, BorderLayout.CENTER);
	}

	public void autoFilling() {
		JTableHeader header = busiDetailTable.getTableHeader();
		int rowCount = busiDetailTable.getRowCount();
		Enumeration columns = busiDetailTable.getColumnModel().getColumns();
		while (columns.hasMoreElements()) {
			TableColumn column = (TableColumn) columns.nextElement();
			int col = header.getColumnModel().getColumnIndex(column.getIdentifier());
			int width = (int) busiDetailTable.getTableHeader().getDefaultRenderer()
					.getTableCellRendererComponent(busiDetailTable, column.getIdentifier(), false, false, -1, col)
					.getPreferredSize().getWidth();
			for (int row = 0; row < rowCount; row++) {
				int preferedWidth = (int) busiDetailTable
						.getCellRenderer(row, col).getTableCellRendererComponent(busiDetailTable,
								busiDetailTable.getValueAt(row, col), false, false, row, col)
						.getPreferredSize().getWidth();
				width = Math.max(width, preferedWidth);
			}
			header.setResizingColumn(column);
			column.setWidth(width + busiDetailTable.getIntercellSpacing().width);
		}
	}

	public void refreshData(int pageNum) {
		// BusiMonitorDao busiMonitordao = new BusiMonitorDaoImpl(new OptTemplate());
		// List<String> conditions = new ArrayList<String>();
		// conditions.add(selectItem.getTranDt());
		// conditions.add(selectItem.getTranCd());
		// conditions.add(selectItem.getMerchId());
		// conditions.add(selectItem.getOpeCd());
		// conditions.add(selectItem.getRspCd());
		// conditions.add(selectItem.getTime());
		// PageModel pml=busiMonitordao.query(pageNum,20,conditions);
		// List<BusiMonitor> list=pml.getList();

		Thread updateThread = new Thread(new Runnable() {
			public void run() {
				synchronized (lock) {
					int index = busiMonitorList.size() - 1;
					BusiMonitor tempBusi = null;
					if (index >= 0) {
						tempBusi = busiMonitorList.get(index);
					}
					if (tempBusi != null) {
						selectItem.setTranSq(tempBusi.getTranSq());
					}

					String sql = selectItem.getSelectSql();
					String[] sqls1 = sql.split("1=1");
					sql = sqls1[0] + "1=1" + " and TIME_STAMP < " + tempBusi.getTimeStamp() + sqls1[1];
					String[] sqls = sql.split("1=1");
					if (selectItem.getTime() != null && !"".equals(selectItem.getTime())) {
						sql = sqls[0] + "1=1"
								+ " and (TIME_STAMP > ((select to_char(systimestamp, 'yyyymmddhh24missff3') from dual) - (to_number("
								+ selectItem.getTime() + " * 100000))))" + sqls[1];
					}

					List<BusiMonitor> dataList = busiMonitorDao.selectPage(sql);
					selectItem.setTranSq(null);
					busiMonitorList.addAll(dataList);
					displayFields(selectItem);
					busiListTableModel.fireTableStructureChanged();
					autoFilling();
					busiListTable.updateUI();
					Thread.yield();
				}
			}
		});
		updateThread.start();

	}

	public void initButtonPanel() {
		JPanel p = new JPanel();
		p.setLayout(new FlowLayout(FlowLayout.LEFT));
		Image startImage = ResourceUtil.getImage(this.getClass().getClassLoader(), "images/start.png");
		JButton startBtn = new JButton("开始更新数据");
		ImageIcon startIcon = new ImageIcon();
		startIcon.setImage(startImage);
		startIcon.setImage(startIcon.getImage().getScaledInstance(23, 23, Image.SCALE_DEFAULT));
		startBtn.setIcon(startIcon);
		startBtn.setBounds(0, 0, 100, 160);

		Image endImage = ResourceUtil.getImage(this.getClass().getClassLoader(), "images/stop.png");
		JButton endBtn = new JButton("停止更新数据");
		ImageIcon endIcon = new ImageIcon();
		endIcon.setImage(endImage);
		endIcon.setImage(endIcon.getImage().getScaledInstance(23, 23, Image.SCALE_DEFAULT));
		endBtn.setIcon(endIcon);
		endBtn.setBounds(0, 0, 100, 160);

		startBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				startMonitor();
			}
		});

		endBtn.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				endMonitor();
			}
		});

		p.setBounds(0, 0, rm.getScreenViewProp().getScreenWidth(), 300);
		p.add(startBtn);
		p.add(endBtn);
		this.add(p, BorderLayout.NORTH);
	}

	public void startMonitor() {
		timer.cancel();
		timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				monitor(selectItem);
			}
		}, 0, 10000);
	}

	public void endMonitor() {
		timer.cancel();
	}

	public void monitor(final Config config) {
		Thread updateThread = new Thread(new Runnable() {
			public void run() {
				synchronized (lock) {
					displayFields(config);
					BusiMonitor firstBusiMonitor = busiMonitorList.get(0);
					if (firstBusiMonitor != null) {
						config.setMonitorTranSq(firstBusiMonitor.getTranSq());
					}

					String sql = selectItem.getSelectSql();
					String[] sqls = sql.split("1=1");
					sql = sqls[0] + "1=1" + " and TIME_STAMP > " + firstBusiMonitor.getTimeStamp() + sqls[1];
					autoFilling();
					List<BusiMonitor> dataList = busiMonitorDao.selectPage(sql);
					busiMonitorList.addAll(0, dataList);
					busiListTableModel.fireTableStructureChanged();
					autoFilling();
					busiDetailTable.updateUI();
					Thread.yield();
				}
			}
		});
		updateThread.start();

	}

	public void displayFields(Config config) {
		busiShowMonitorList.clear();
		rowData = new String[100][22];
		Boolean[] displayArr = new Boolean[22];
		if (config != null) {
			String display = config.getDisplay();
			if (display == null) {
				display = "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0";
			}

			// busiShowMonitorList.addAll(busiMonitorList);
			String[] temp1 = display.split(",");
			for (int i = 0; i < temp1.length; i++) {
				// String str = String.valueOf(temp[i]);
				if ("1".equals(temp1[i])) {
					displayArr[i] = true;
				} else {
					displayArr[i] = false;
				}
			}
		}
		String[] tempColumnNames = { "清算日期(TRAN_DT)", "交易码(TRAN_CD)", "委托单位代码(MERCH_ID)", "业务代码(OPE_CD)", "响应码(RSP_CD)",
				"中心流水号(TRAN_SQ)", "交易简称(TRAN_ABBR_NM)", "机构代码(INST_ID)", "机构类型(NODE_TYPE)", "前端流水号(SOLE_FRONT_SQ)",
				"渠道代码(CHNL_CD)", "交易时间戳(TIME_STAMP)", "交易状态(TRAN_STATE_CD)", "操作员(TLR_ID)", "账号(ACC_CARD_ID)",
				"交易金额(TRAN_AT)", "业务专号(PAY_ID)", "交易日志文件名(LOGFILE_NAME)", "交易日志单号(LOG_ID)", "交易耗时(TX_USE_TIME)",
				"响应描述(RET_DESC)", "前端服务器代码(SERVER_CD)" };
		columnNames.clear();
		for (int i = 0; i < tempColumnNames.length; i++) {
			if (displayArr[i]) {
				columnNames.add(tempColumnNames[i]);
			}
		}

		// char[] temp =display.toCharArray();

		for (int i = 0; i < busiMonitorList.size(); i++) {
			int j = 0;
			BusiMonitor bm = busiMonitorList.get(i);
			String[] arr = new String[100];
			if (bm != null) {
				for (int k = 0; k < displayArr.length; k++) {
					boolean isDisplay = displayArr[k];
					String str = "";

					if (k == 0) {
						str = bm.getTranDt();
					} else if (k == 1) {
						str = bm.getTranCd();
					} else if (k == 2) {
						str = bm.getMerchId();
					} else if (k == 3) {
						str = bm.getOpeCd();
					} else if (k == 4) {
						str = bm.getRspCd();
					} else if (k == 5) {
						str = bm.getTranSq();
					} else if (k == 6) {
						str = bm.getTranAbbrNm();
					} else if (k == 7) {
						str = bm.getInstId();
					} else if (k == 8) {
						str = bm.getNodeType();
					} else if (k == 9) {
						str = bm.getSoleFrontSq();
					} else if (k == 10) {
						str = bm.getChnlCd();
					} else if (k == 11) {
						str = bm.getTimeStamp();
					} else if (k == 12) {
						str = bm.getTranStateCd();
					} else if (k == 13) {
						str = bm.getTlrId();
					} else if (k == 14) {
						str = bm.getAccCardId();
					} else if (k == 15) {
						str = bm.getTranAt();
					} else if (k == 16) {
						str = bm.getPayId();
					} else if (k == 17) {
						str = bm.getLogfileName();
					} else if (k == 18) {
						str = bm.getLogId();
					} else if (k == 19) {
						str = bm.getTxUseTime();
					} else if (k == 20) {
						str = bm.getRetDesc();
					} else if (k == 21) {
						str = bm.getServerCd();
					}
					if (isDisplay) {
						arr[j] = str;
						j++;
					}
				}
				busiShowMonitorList.add(i, arr);
			}

		}

		busiListTableModel.fireTableStructureChanged();
		busiDetailTable.updateUI();
	}

	class BusiConfigTableModel extends AbstractTableModel {
		public int getColumnCount() {
			return configColumnNames.length;
		}

		public int getRowCount() {
			return configRowData.length;
		}

		public Object getValueAt(int row, int col) {
			return configRowData[row][col];
		}

		public String getColumnName(int column) {
			return configColumnNames[column];
		}
	}

	class BusiListTableModel extends AbstractTableModel {
		public int getColumnCount() {
			return columnNames.size();
		}

		public int getRowCount() {
			return busiShowMonitorList.size();
		}

		public Object getValueAt(int row, int col) {
			// TODO 
			return busiShowMonitorList.get(row)[col];

		}

		public String getColumnName(int column) {
			return "   " + columnNames.get(column) + "   ";
		}
	}

}
